module jlib;
import StdEnv, Scanner;

/* This program was based on a method for metaprogramming
proposed by Jorlano Donizetti, who also is the author
of the java calls for this library. By the way, Jorlano
works on the theoretical aspects of critical applications
(like air taffic control, and nuclear power contingency
analysis, and also on applications for cell phone. It seems
that he earns his wages with the cell phones :-) */

Start world
   # (ok, inFile, world)= fopen "japilib.c" FReadText world;
   | not ok= abort "I cannot open japilib.c\n";
   # (prog, inFile)= getList inFile; 
     (ok, world)= fclose inFile world;
     (ok, outFile, world)= fopen "jlib.def" FWriteText world;
     outFile = putList outFile prog ;
     (ok, world)= fclose outFile world;    
   = world;

stripNewLine s
  | size s > 0 && s.[size s - 1] == '\n'= s%(0, size s - 2);
  = s;

cns x ["","":xs]= [x, "":xs];
cns x xs= [x:xs];

getList inFile = loop inFile;
where {
  loop inFile 
    # (ok, inFile)= fend inFile;
    | ok= ([], inFile);
    # (x, inFile)= freadline inFile;
      (xs, inFile)= loop inFile;
    = (cns (stripNewLine x) xs, inFile);
}

putList outFile xs
  # outFile= fwrites "[" outFile;
  # outFile= loop outFile  xs;
  # outFile= fwrites "]" outFile;
  = outFile;
where {
  wrap x= "\""+++x+++"\"";
  loop outFile []= outFile;
  loop outFile [x]
   # outFile= fwrites (wrap x) outFile;
   = outFile;
  loop outFile [x:xs]
     # outFile= fwrites (wrap x) outFile;
     # outFile= fwrites ",\n" outFile;
     = loop outFile xs;
}

